package com.example.admin.mybledemo.ui;

import android.app.Application;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.example.admin.mybledemo.BleRssiDevice;
import com.example.admin.mybledemo.ota.OtaState;

import cn.com.heaton.blelibrary.ble.model.BleDevice;

public class OtaViewModel extends AndroidViewModel implements OtaService.OtaServiceCallback {

    private OtaService otaService;
    private boolean isServiceBound = false;

    private final MutableLiveData<OtaState> _otaState = new MutableLiveData<>(OtaState.IDLE);
    public LiveData<OtaState> otaState = _otaState;

    private final MutableLiveData<Integer> _progress = new MutableLiveData<>(0);
    public LiveData<Integer> progress = _progress;

    private final MutableLiveData<String> _logMessages = new MutableLiveData<>("");
    public LiveData<String> logMessages = _logMessages;

    private final MutableLiveData<String> _errorMessages = new MutableLiveData<>();
    public LiveData<String> errorMessages = _errorMessages;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            OtaService.OtaBinder binder = (OtaService.OtaBinder) service;
            otaService = binder.getService();
            otaService.setCallback(OtaViewModel.this);
            isServiceBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isServiceBound = false;
        }
    };

    public OtaViewModel(@NonNull Application application) {
        super(application);
        Intent intent = new Intent(application, OtaService.class);
        application.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
    }

    public void startOta(BleRssiDevice device, Uri fileUri, String macCode, String creditCode) {
        Intent serviceIntent = new Intent(getApplication(), OtaService.class);
        // 传递设备属性而不是对象本身，避免Parcelable问题
        serviceIntent.putExtra("deviceAddress", device.getBleAddress());
        serviceIntent.putExtra("deviceName", device.getBleName());
        serviceIntent.putExtra("fileUri", fileUri);
        serviceIntent.putExtra("macCode", macCode);
        serviceIntent.putExtra("creditCode", creditCode);
        serviceIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        getApplication().startService(serviceIntent);
    }

    public void cancelOta() {
        _logMessages.postValue("用户取消OTA升级...");
        if (isServiceBound && otaService != null) {
            otaService.stopOta();
        } else {
            // 如果服务没有绑定，直接停止服务
            Intent serviceIntent = new Intent(getApplication(), OtaService.class);
            getApplication().stopService(serviceIntent);
        }
        
        // 确保状态被重置为IDLE，允许重新开始OTA
        _otaState.postValue(OtaState.IDLE);
        _progress.postValue(0);
        _logMessages.postValue("OTA已取消，可以重新开始升级");
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        if (isServiceBound) {
            getApplication().unbindService(serviceConnection);
            isServiceBound = false;
        }
    }

    // OtaServiceCallback implementation
    @Override
    public void onStateChanged(OtaState state) {
        _otaState.postValue(state);
        _logMessages.postValue("State changed: " + state.getDescription());
    }

    @Override
    public void onProgressChanged(int progress, int total) {
        _progress.postValue((int) ((double) progress / total * 100));
    }

    @Override
    public void onError(int errorCode, String errorMessage) {
        _errorMessages.postValue(errorMessage);
    }

    @Override
    public void onSuccess() {
        _logMessages.postValue("OTA Success!");
    }
}
